import {Component, Input, OnInit} from '@angular/core';
import {DeviceStatus} from '../../../used-store-manage.pipe';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzModalRef, NzModalService} from 'ng-zorro-antd/modal';
import {UsedStorePService} from '../../../used-store-p.service';
import {UsedStoreZservice} from '../../../used-store-zservice';

@Component({
  selector: 'app-out-store-select-device',
  templateUrl: './out-store-select-device.component.html',
  styleUrls: ['./out-store-select-device.component.scss']
})
export class OutStoreSelectDeviceComponent implements OnInit {
  @Input() equipmentCodes: any = '';
  DEVICESTATUS = DeviceStatus;
  query = {
    code: null, // 编码
    libraryId: [], // 编码
    typeId: [], // 设备品牌
    modelId: [], // 设备型号
    finished: [], // 设备型号
    page: 1, // 当前页
    pageSize: 20, // 分页大小
  };
  listOfData: any = {
    page: 1,
    total: 100,
    pageSize: 20,
    records: []
  };
  modal = {
    modalVisible: false,
    operationType: '',
    loading: false,
  };
  formData = {
    id: '',
    date: '',
    productId: '',
    registerCount: 0,
    rechargeAmount: 0,
  };
  appOptions: any[] = [];
  // 选择
  checked = false;
  indeterminate = false;
  setOfCheckedId = new Set<number>();
  // 品牌待选项
  brandOptions: any[] = [];
  // 机型待选项
  typeOptions: any[] = [];
  // 库位待选项
  locationOptions: any[] = [];


  constructor(
    private nzMessageService: NzMessageService,
    private nzModalService: NzModalService,
    private nzModalRef: NzModalRef,
    private usedStorePService: UsedStorePService,
    private usedStoreZservice: UsedStoreZservice,
  ) {
  }

  ngOnInit(): void {
    this.queryList();
    this.usedStorePService.getBrandList().then((res: any) => {
      if (res.code === 0) {
        this.brandOptions = res.data.records;
      }
    });
    this.usedStoreZservice.recycleLibraryList({page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.locationOptions = res.data.records;
      }
    });
  }

  getTypeList() {
    this.query.modelId = [];
    if (!this.query.typeId.join(',')) {
      this.typeOptions = [];
      return;
    }
    this.usedStorePService.getTypeList(this.query.typeId.join(',')).then((res: any) => {
      if (res.code === 0) {
        this.typeOptions = res.data.records;
      }
    });
  }

  queryBtn() {
    this.query.page = 1;
    this.queryList();
  }

  resetQuery() {
    this.query = {
      code: null, // 编码
      libraryId: [], // 编码
      typeId: [], // 设备品牌
      modelId: [], // 设备型号
      finished: [], // 设备型号
      page: 1, // 当前页
      pageSize: 20, // 分页大小
    };
    this.queryList();
  }

  // 查询列表
  queryList(): void {
    // @ts-ignore
    const beginClinchTime = this.usedStorePService.formatTime(this.query.finished ? this.query.finished[0] : '', 'date');
    // @ts-ignore
    const endClinchTime = this.usedStorePService.formatTime(this.query.finished ? this.query.finished[1] : '', 'date');
    this.usedStorePService.getDevices({
      ...this.query,
      beginClinchTime,
      endClinchTime,
      libraryId: this.query.libraryId.join(','),
      typeId: this.query.typeId.join(','),
      modelId: this.query.modelId.join(','),
      status: '0',
      occupyStatus: '0',
      // @ts-ignore
      source: 0,
    }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data;
        if (this.equipmentCodes) {
          this.setOfCheckedId = new Set(JSON.parse(this.equipmentCodes));
          this.refreshCheckedStatus();
        }
      }
    });
  }

  onPageIndexChange(index: number) {
    this.query.page = index;
    this.queryList();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.queryList();
  }

  // 删除
  deleteRow(id: any) {
    // this.(id).then((res: any) => {
    //   if (res.code === 0) {
    //     this.nzMessageService.success('删除成功');
    //     this.queryList();
    //   }
    // });
  }

  // 放到二手商城销售或者取回
  takeToShopping(data: any) {
    this.nzModalService.confirm({
      nzTitle: '<i>提示</i>',
      nzContent: '<b>确认将机器放到二手商城销售？</b>',
      nzOnOk: () => console.log('OK')
    });
  }

  onAllChecked(checked: boolean): void {
    this.listOfData.records
      // @ts-ignore
      .filter(({disabled}) => !disabled)
      // @ts-ignore
      .forEach(({equipmentCode}) => this.updateCheckedSet(equipmentCode, checked));
    this.refreshCheckedStatus();
  }

  updateCheckedSet(equipmentCode: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(equipmentCode);
    } else {
      this.setOfCheckedId.delete(equipmentCode);
    }
  }

  refreshCheckedStatus(): void {
    // @ts-ignore
    const listOfEnabledData = this.listOfData.records.filter(({disabled}) => !disabled);
    // @ts-ignore
    this.checked = listOfEnabledData.every(({equipmentCode}) => this.setOfCheckedId.has(equipmentCode));
    // @ts-ignore
    this.indeterminate = listOfEnabledData.some(({equipmentCode}) => this.setOfCheckedId.has(equipmentCode)) && !this.checked;
  }

  onItemChecked(equipmentCode: number, checked: boolean): void {
    this.updateCheckedSet(equipmentCode, checked);
    this.refreshCheckedStatus();
  }


  save() {
    if (!this.setOfCheckedId.size) {
      this.nzMessageService.warning('没有选中数据');
      return;
    }
    this.nzModalRef.destroy({
      data: this.listOfData.records.filter((i: any) => this.setOfCheckedId.has(i.equipmentCode)).map((i: any) => ({
        ...i,
        firstTime: i.createTime
      }))
    });
  }
}

